package com.jk1123.us.core.datasource;

import com.zaxxer.hikari.HikariDataSource;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.bind.Bindable;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.core.env.Environment;

import java.util.concurrent.TimeUnit;

/**
 * @author huyoufu <https://github.com/huyoufu>
 * @TIME 2021-09-16 22:46
 * @description
 */
@ConfigurationProperties("us.datasource")
@Data
public class UsDataSourceProperties {
    public static final long DEFAULT_CONNECTION_TIMEOUT = TimeUnit.SECONDS.toMillis(30L);

    public static final long DEFAULT_VALIDATION_TIMEOUT = TimeUnit.SECONDS.toMillis(10L);

    public static final int DEFAULT_MAX_POOL_SIZE = 20;

    public static final int DEFAULT_MINIMUM_IDLE = 2;

    private final HikariDataSource dataSource;

    private UsDataSourceProperties() {
        dataSource = new HikariDataSource();
        dataSource.setConnectionTimeout(DEFAULT_CONNECTION_TIMEOUT);
        dataSource.setValidationTimeout(DEFAULT_VALIDATION_TIMEOUT);
        dataSource.setMaximumPoolSize(DEFAULT_MAX_POOL_SIZE);
        dataSource.setMinimumIdle(DEFAULT_MINIMUM_IDLE);
    }

    /**
     * Build new Hikari config.
     *
     * @return new hikari config
     */
    public static UsDataSourceProperties build(Environment environment) {
        UsDataSourceProperties result = new UsDataSourceProperties();
        Binder.get(environment).bind("db.pool.config", Bindable.ofInstance(result.getDataSource()));
        return result;
    }

    /**
     * Fully qualified name of the JDBC driver. Auto-detected based on the URL by default.
     */
    private String driverClassName;

    /**
     * JDBC URL of the database.
     */
    private String url;

    /**
     * Login username of the database.
     */
    private String username;

    /**
     * Login password of the database.
     */
    private String password;

}
